package com.yexx.nacos.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.yexx.nacos.api.DiscoveryApi;
import com.yexx.nacos.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Slf4j
@RestController
public class DiscoveryController implements DiscoveryApi {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StorageService storageService;

    @Override
    @SentinelResource(value = "discovery-get")
    @Transactional
    public String get(String serviceName) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        String targetUrl = instances.get(0).getUri() + "/discovery/echo?name=" + "123";
        String response = restTemplate.getForObject(targetUrl, String.class);

        decr(1);
        //制造回滚
//        int i = 1/ 0;
        return response;
    }

    @Override
    public String echo(String name) {
        return "欢迎你:" + name;
    }

    @Override
    public String decr(Integer decr) {
        return storageService.decr(decr);
    }
}